require(['jquery', 'underscore','Mustache','Utils', 'echarts', 'echarts/chart/bar', 'echarts/chart/line'],
function($, _, Mustache, Utils, ec) {
	
	$('.audit-container').hide();
                    
	var searchObj=Utils.search_parse();
	var eid=searchObj.eid;
	if(!eid){
		return;
	}
	var wordMap={
		tableName:'表名',
		rows:'记录数',
		dataSize:'数据量',
		columnName:'字段名',
		columnType:'字段类型',
	};
	var internal=['name','qualifiedName','type','source','createTime','updateTime','owner','bussinessName','description',];
	var hide=['id','classname','version'];
	var internalObj=_.invert(internal);
	var hideObj=_.invert(hide);
	var fieldTemplate='<li class="list-group-item">'
        			+'<span class="inlineb wid-40p text-rig fname">{{fname}}:</span><span class="inlineb wid-60p pad-left-10 fvalue">{{fvalue}}</span>'
      				+'</li>';
    var schemaTemplate='<li><span class="inlineb mar-top-10 wid-50p text-cen">{{a}}</span><span class="inlineb wid-50p text-cen">{{b}}</span></li>';
	$.getJSON('/entity/detail/'+eid,function(res){
		var entity = res.entity;
		var schema = res.schema;
		var audit = res.audit;
		//detail
		$('#entity-name').text(entity.name);
		var entityContainer=$('#entity-container');
		for(var i in internal){
			var fname=internal[i];
			var fvalue=entity[fname];
			if(fname=='createTime'||fname=='updateTime'){
				fvalue=Utils.time_format(fvalue,'yyyy-MM-dd hh:mm:ss');
			}
			var data={fname:fname,fvalue:fvalue};
			entityContainer.append(Mustache.render(fieldTemplate,data));
		}
		for(var fname in entity){
			if((fname in internalObj) || (fname in hideObj)){
				continue;
			}
			entityContainer.append(Mustache.render(fieldTemplate,{fname:fname,fvalue:entity[fname]}));
		}
		//schema
		do {
			var schemaContainer = $('#schema-container');
			var auditContainer = $('#audit-word-container');

			var cname=entity.classname.split('.');
			var columnAName, columnA=schema.columnA, columnBName, columnB=schema.columnB;
			if(!columnA){
				schemaContainer.append('<li>该实体类型没有更多的信息</li>');
				break;
			}
			cname=cname[cname.length-1];
			switch(cname){
				case 'MySQLDatabase':
				columnAName='表名';
				columnBName='记录数';
				break;
				case 'MySQLTable':
				columnAName='字段名';
				columnBName='字段类型';
				break;
				case 'MongoDBDatabase':
				columnAName='集合名';
				columnBName='数据量';
				break;
				case 'KettleTransform':
				columnAName='步骤';
				columnBName='源类型';
				showGraph(res, ec, ["errors", "input", "output"]);
				break;
				case 'KettleStep':
				showGraph(res, ec, ["errors", "read", "write"]);
				break;
			}
			schemaContainer.append(Mustache.render(schemaTemplate,{a:columnAName, b:columnBName}));
			if(columnA.length != columnB.length){
				throw 'column a and column b size not equal';
			}
			for(var i in columnA){
				schemaContainer.append(Mustache.render(schemaTemplate, {a: columnA[i], b: columnB[i]}));
			}
		} while (0);

		// audit
		var auditTitle = audit.title;
		var auditContent = audit.content;
		if (!auditTitle) {
			auditContainer.append('<li>该实体类型没有审计信息</li>')
			return;
		}

		auditContainer.append(Mustache.render(schemaTemplate, {a: "审计信息", b: "内容"}));
		for (var i in auditTitle) {
			auditContainer.append(Mustache.render(schemaTemplate, {a: auditTitle[i], b: auditContent[i]}));
		}
	});
});

function showGraph(res, ec, requireList) {
	var records = res.records;
	if (!(records && records.length > 0)) {
		return;
	}

	var xList = [];
	var yList = [];
	var errorList = [];

	var startDate = new Date(records[0].date.substr(0, 10));
	var endDate = new Date(records[records.length-1].date.substr(0, 10));
	var oneDay = 1 * 24 * 60 * 60 * 1000;

	var dateMap = getDetailData(records, requireList, startDate, endDate);
	var dateCountMap = dateMap['count'];
	var detailList = [];
	var serise = [];

	_.each (requireList, function(e, i){
		detailList.push(dateMap[e]);
		serise.push({'name': e, type: 'line', data: []})
	});

	for (var d = startDate; d <= endDate; d = new Date(d.getTime()+oneDay)) {
		var dateStr = d.format("yyyy-MM-dd")
		xList.push(dateStr);
		if (dateCountMap[dateStr]) {
			yList.push(dateCountMap[dateStr]);
		} else {
			yList.push(0);
		}
		
		_.each(detailList, function(detailMap, i){
			if (detailMap[dateStr]) {
				serise[i].data.push(detailMap[dateStr]);
			} else {
				serise[i].data.push(0);
			}
		})
	}
	var main = showMainGraph(ec, xList, yList);
	var detail = showDetail(ec, xList, serise);
	main.connect(detail);
	detail.connect(main);
}

function getDetailData(records, requireList, startDate, endDate) {
	var dateCountMap = new Array();
	var dateMap = new Array();
	dateMap['count'] = dateCountMap;
	_.each(requireList, function (e, i){
		dateMap[e] = new Array();
	});

	var oneDay = 1 * 24 * 60 * 60 * 1000;

	for (var d = startDate; d <= endDate; d = new Date(d.getTime() + oneDay)) {
		var dateStr = d.format("yyyy-MM-dd")
		_.each (requireList, function(label, i) {
			dateMap[label][dateStr] = 0;
		});
		dateCountMap[dateStr] = 0;
	}

	_.each (records, function(e, i) {
		var dateStr = e.date.substr(0, 10);
		_.each(requireList, function(label, i1) {
			dateMap[label][dateStr] += parseInt(e[label]);
		});
		dateCountMap[dateStr] += 1;
	});
	return dateMap;
}

function showMainGraph(ec, xList, yList) {
	var option = {
	    tooltip : {
	        trigger: 'axis'
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: false},
	            dataZoom : {show: true},
	            dataView : {show: true},
	            magicType : {show: true, type: ['line', 'bar']},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    dataZoom : {
	        show : true,
	        realtime : true,
	        //orient: 'vertical',   // 'horizontal'
	        //x: ,
	        y: 25,
	        // width: 400,
	        // height: 20,
	        // backgroundColor: 'rgba(221,160,221,0.5)',
	        // dataBackgroundColor: 'rgba(138,43,226,0.5)',
	        // fillerColor: 'rgba(38,143,26,0.6)',
	        // handleColor: 'rgba(128,43,16,0.8)',
	        // xAxisIndex:[],
	        // yAxisIndex:[],
	        // start : 40,
	        // end : 60
	    },
	    xAxis : [
	        {
	            type: 'category',
	            boundaryGap: false,
	            data: xList
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
	    series : [
	        {
	            name: '运行次数',
	            type: 'line',
	            data: yList
	        }
	    ],
	    calculable:false  
	};
	var container = $('#record-container');
	container.height(window.screen.availHeight * 0.35);
	container.width(document.body.clientWidth * 0.5);
	var myChart = ec.init(container[0]);
	myChart.setOption(option);
	return myChart;
}

function showDetail(ec, xList, yList) {
	var option = {
	    tooltip : {
	        trigger: 'axis'
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: false},
	            dataZoom : {show: true},
	            dataView : {show: true},
	            magicType : {show: true, type: ['line', 'bar']},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    xAxis : [
	        {
	            type: 'category',
	            boundaryGap: false,
	            data: xList
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
	    series : yList,
	    calculable: false
	};
	var container = $('#detail-container');
	container.height(window.screen.availHeight * 0.2);
	container.width(document.body.clientWidth * 0.5);
	var myChart = ec.init(container[0]);
	myChart.setOption(option);
	return myChart;
}

function clickSchema() {
    $('#audit-select').removeClass('active');
    $('#schema-select').addClass('active');

    $('.audit-container').hide();
    $('#schema-container').fadeIn(300);
}

function clickAudit() {
    $('#schema-select').removeClass('active');
    $('#audit-select').addClass('active');

    $('#schema-container').hide();
    $('.audit-container').fadeIn(300);
}